<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="物料类型">
              <j-dict-select-tag
                placeholder="请选择物料类型"
                v-model="queryParam.materialType"
                dictCode="material_type"
                @change="handleMaterialTypeChange"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="物料编号">
              <a-input placeholder="请输入物料编号" v-model="queryParam.materialCode" allowClear />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="系列">
              <a-input placeholder="请输入系列" v-model="queryParam.materialSeries" allowClear />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="颜色">
              <a-input placeholder="请输入颜色" v-model="queryParam.color" allowClear />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓库">
              <j-select-warehouse
                placeholder="请选择仓库"
                v-model="queryParam.warehouseId"
                @change="handleWarehouseChange"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="库位">
              <j-select-warehouse-location
                placeholder="请选择库位"
                v-model="queryParam.locationId"
                :warehouse-id="warehouseId"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="批次号">
              <a-input placeholder="请输入批次号" v-model="queryParam.batchNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="库存状态">
              <j-dict-select-tag
                placeholder="请选择库存状态"
                v-model="queryParam.stockStatus"
                dictCode="wms_stock_status"
              />
            </a-form-item>
          </a-col>
          <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="计划入库时间">
              <a-date-picker
                style="width: 100%"
                v-model="queryParam.planInboundTime"
                placeholder="请选择计划入库日期"
                format="YYYY-MM-DD"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="实际入库时间">
              <a-date-picker
                style="width: 100%"
                v-model="queryParam.actualInboundTime"
                placeholder="请选择实际入库日期"
                format="YYYY-MM-DD"
              />
            </a-form-item>
          </a-col> -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls('库存列表')">导出</a-button>
      <a-button type="primary" icon="history" @click="handleHistory" v-if="hasPermission('wms:inventory:history')"
        >历史</a-button
      >
      <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :action="importExcelUrl"
        @change="handleImportExcel"
        v-if="hasPermission('wms:inventory:import')"
      >
        <!-- <a-button type="primary" icon="import">导入</a-button> -->
      </a-upload>
    </div>

    <!-- table区域-begin -->
    <div class="table-wrapper">
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: 1800, y: 'calc(100vh - 350px)', scrollToFirstRowOnChange: false }"
        @change="handleTableChange"
      >
        <template slot="stockStatusSlot" slot-scope="text, record">
          <a-tag :color="getStockStatusColor(record.stockStatus)">
            {{ record.stockStatusName || '-' }}
          </a-tag>
        </template>

        <template slot="materialTypeSlot" slot-scope="text, record">
          <a-tag :color="getMaterialTypeColor(record.materialType)">
            <j-dict-label :value="record.materialType" dictCode="material_type" />
          </a-tag>
        </template>
        <template slot="materialImagesSlot" slot-scope="text, record">
          <span v-if="record.materialImages">
            <img
              :src="getImageUrl(record.materialImages)"
              height="40"
              alt="物料图片"
              @click="handlePreview(record.materialImages)"
              style="cursor: pointer"
              @error="handleImageError"
            />
            <span v-if="getImageCount(record.materialImages) > 1" style="margin-left: 5px">
              +{{ getImageCount(record.materialImages) - 1 }}
            </span>
          </span>
          <span v-else>-</span>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)" v-if="hasPermission('wms:inventory:edit')">编辑</a>
          <a-divider
            type="vertical"
            v-if="
              hasPermission('wms:inventory:edit') &&
              (hasPermission('wms:inventory:history') || hasPermission('wms:inventory:adjust'))
            "
          />
          <a @click="handleAdjust(record)" v-if="hasPermission('wms:inventory:adjust')" style="color: #1890ff">调整</a>
          <a-divider
            type="vertical"
            v-if="hasPermission('wms:inventory:adjust') && hasPermission('wms:inventory:history')"
          />
          <a @click="handleHistory(record)" v-if="hasPermission('wms:inventory:history')">历史</a>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 模态框区域 -->
    <inventory-history-modal ref="historyModal"></inventory-history-modal>
    <inventory-edit-modal ref="editModal" @ok="handleModalOk"></inventory-edit-modal>

    <!-- 库存调整模态框 -->
    <a-modal
      :title="'库存调整 - ' + (adjustRecord.materialName || '')"
      :visible="adjustVisible"
      :confirmLoading="adjustLoading"
      @ok="handleAdjustOk"
      @cancel="handleAdjustCancel"
      width="600px"
      :destroyOnClose="true"
    >
      <a-form-model
        ref="adjustForm"
        :model="adjustForm"
        :rules="adjustRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="物料编号">
              <a-input :value="adjustRecord.materialCode" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="当前库存">
              <a-input :value="adjustRecord.quantity + ' ' + (adjustRecord.unit || '')" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="仓库">
              <a-input :value="adjustRecord.warehouseName" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="库位">
              <a-input :value="adjustRecord.locationName" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-form-model-item label="调整类型" prop="adjustType">
          <a-radio-group v-model="adjustForm.adjustType" @change="onAdjustTypeChange">
            <a-radio value="increase">增加库存</a-radio>
            <a-radio value="decrease">减少库存</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="调整数量" prop="quantity">
          <a-input-number
            v-model="adjustForm.quantity"
            :min="0.01"
            :max="adjustForm.adjustType === 'decrease' ? adjustRecord.quantity : 999999"
            :precision="2"
            style="width: 100%"
            placeholder="请输入调整数量"
          />
        </a-form-model-item>
        <a-form-model-item label="调整原因" prop="reason">
          <a-textarea v-model="adjustForm.reason" :rows="3" placeholder="请输入调整原因" :maxLength="200" show-count />
        </a-form-model-item>
        <a-form-model-item label="预计调整后">
          <a-input :value="getAdjustedQuantity() + ' ' + (adjustRecord.unit || '')" disabled />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 图片预览 -->
    <a-modal
      :visible="previewVisible"
      :footer="null"
      @cancel="handleClosePreview"
      width="90%"
      :destroyOnClose="true"
      :maskClosable="true"
      wrapClassName="image-preview-modal"
      :title="`物料图片预览 (共${previewImages.length}张)`"
    >
      <div class="image-preview-container" tabindex="0" ref="previewContainer" @keydown="handleKeyDown">
        <!-- 视图切换按钮 -->
        <div class="view-toggle-container">
          <a-radio-group v-model="showLargePreview" button-style="solid">
            <a-radio-button :value="false"> <a-icon type="appstore" /> 网格视图 </a-radio-button>
            <a-radio-button :value="true"> <a-icon type="picture" /> 大图视图 </a-radio-button>
          </a-radio-group>
        </div>

        <!-- 图片网格布局 -->
        <div class="image-grid-container" v-show="!showLargePreview">
          <div
            v-for="(image, index) in previewImages"
            :key="index"
            class="image-grid-item"
            :class="{ active: currentImageIndex === index }"
            @click="selectImage(index)"
          >
            <a-spin :spinning="imageLoading" tip="加载中...">
              <img :src="image" alt="物料图片" @error="handleImageError" @load="handleImageLoad" />
            </a-spin>
            <div class="image-grid-item-index">{{ index + 1 }}</div>
          </div>
        </div>

        <!-- 选中图片大图预览 -->
        <div class="image-preview-selected" v-if="previewImages.length > 0 && showLargePreview">
          <div class="image-slide">
            <a-spin :spinning="imageLoading" tip="图片加载中...">
              <img
                :src="previewImages[currentImageIndex]"
                :style="{ transform: `rotate(${imageRotation}deg) scale(${imageScale})` }"
                alt="物料图片"
                @error="handleImageError"
                @load="handleImageLoad"
              />
            </a-spin>
          </div>
          <div class="image-preview-counter">{{ currentImageIndex + 1 }}/{{ previewImages.length }}</div>
          <div class="image-preview-controls">
            <a-button-group>
              <a-button icon="zoom-in" @click="zoomIn" title="放大"></a-button>
              <a-button icon="zoom-out" @click="zoomOut" title="缩小"></a-button>
              <a-button icon="fullscreen" @click="toggleFullscreen" title="全屏"></a-button>
              <a-button icon="download" @click="downloadImage" title="下载"></a-button>
              <a-button icon="undo" @click="rotateLeft" title="向左旋转"></a-button>
              <a-button icon="redo" @click="rotateRight" title="向右旋转"></a-button>
              <a-button icon="reload" @click="resetImage" title="重置"></a-button>
            </a-button-group>
            <a-button-group v-if="previewImages.length > 1" style="margin-left: 10px">
              <a-button icon="left" @click="prevImage" title="上一张"></a-button>
              <a-button icon="right" @click="nextImage" title="下一张"></a-button>
            </a-button-group>
            <a-button icon="close" @click="handleClosePreview" style="margin-left: 10px" title="关闭"></a-button>
          </div>
        </div>
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JDictLabel from '@/components/dict/JDictLabel.vue'
import JSelectWarehouse from '@/components/jeecgbiz/JSelectWarehouse'
import JSelectWarehouseLocation from '@/components/jeecgbiz/JSelectWarehouseLocation'
import JSelectMaterial from '@/components/jeecgbiz/JSelectMaterial'
import { inventoryList, inventoryExport } from '@/api/wms'
import InventoryHistoryModal from './modules/InventoryHistoryModal'
import InventoryEditModal from './modules/InventoryEditModal'
import { USER_AUTH, SYS_BUTTON_AUTH } from '@/store/mutation-types'
import 'vue-photo-preview/dist/skin.css'
import preview from 'vue-photo-preview'
import Vue from 'vue'
import { getFileAccessHttpUrl } from '@/api/manage'
import moment from 'moment'

// 注册图片预览组件
preview.install(Vue, {
  fullscreenEl: false,
})

export default {
  name: 'InventoryList',
  mixins: [JeecgListMixin],
  components: {
    JDictSelectTag,
    JDictLabel,
    JSelectWarehouse,
    JSelectWarehouseLocation,
    JSelectMaterial,
    InventoryHistoryModal,
    InventoryEditModal,
  },
  data() {
    return {
      description: '库存管理',
      // 查询条件
      queryParam: {
        materialCode: '',
        materialName: '',
        materialType: '',
        warehouseId: '',
        locationId: '',
        batchNo: '',
        stockStatus: '',
        planInboundTime: null, // 计划入库时间
        actualInboundTime: null, // 实际入库时间
      },
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '仓库',
          align: 'center',
          dataIndex: 'warehouseName',
          width: 120,
        },
        {
          title: '库位',
          align: 'center',
          dataIndex: 'locationName',
          width: 120,
        },
        {
          title: '库存数量',
          align: 'center',
          dataIndex: 'quantity',
          width: 100,
        },
        {
          title: '物料编码',
          align: 'center',
          dataIndex: 'materialCode',
          width: 120,
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName',
          width: 150,
        },
        {
          title: '系列',
          align: 'center',
          dataIndex: 'materialSeries',
          width: 150,
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType',
          width: 100,
          scopedSlots: { customRender: 'materialTypeSlot' },
        },
        {
          title: '规格',
          align: 'center',
          dataIndex: 'specification',
          width: 100,
        },
        {
          title: '颜色',
          align: 'center',
          dataIndex: 'color',
          width: 150,
        },
        {
          title: '物料长度（m）',
          align: 'center',
          dataIndex: 'materialLength',
          width: 120,
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit',
          width: 80,
        },
        {
          title: '可用数量',
          align: 'center',
          dataIndex: 'availableQuantity',
          width: 100,
        },
        {
          title: '预分配数量',
          align: 'center',
          dataIndex: 'preOutboundQuantity',
          width: 100,
        },
        {
          title: '单位成本',
          align: 'center',
          dataIndex: 'unitCost',
          width: 100,
          customRender: (text) => {
            return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00'
          },
        },
        {
          title: '总成本',
          align: 'center',
          dataIndex: 'totalCost',
          width: 100,
          customRender: (text) => {
            return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00'
          },
        },
        {
          title: '批次号',
          align: 'center',
          dataIndex: 'batchNo',
          width: 120,
        },

        {
          title: '物料图片',
          align: 'center',
          dataIndex: 'materialImages',
          width: 100,
          scopedSlots: { customRender: 'materialImagesSlot' },
        },
        {
          title: '库存状态',
          align: 'center',
          dataIndex: 'stockStatus',
          width: 100,
          scopedSlots: { customRender: 'stockStatusSlot' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 120,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/wms/inventory/queryInventoryPageList',
        delete: '/wms/inventory/delete',
        deleteBatch: '/wms/inventory/deleteBatch',
        exportXlsUrl: '/wms/inventory/exportInventoryList',
        importExcelUrl: 'wms/inventory/importExcel',
      },
      warehouseId: '',
      dictOptions: {},
      toggleSearchStatus: false,
      materialType: '',
      // 权限相关
      permissionList: [],
      inboundType: '11',
      // 库存调整相关
      adjustVisible: false,
      adjustLoading: false,
      adjustRecord: {},
      adjustForm: {
        adjustType: 'increase',
        quantity: null,
        reason: '',
      },
      adjustRules: {
        adjustType: [{ required: true, message: '请选择调整类型', trigger: 'change' }],
        quantity: [
          { required: true, message: '请输入调整数量', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '调整数量必须大于0', trigger: 'blur' },
        ],
        reason: [{ required: true, message: '请输入调整原因', trigger: 'blur' }],
      },
      // 预览相关
      previewVisible: false,
      previewImage: '',
      previewImages: [], // 用于存储所有预览图片
      currentImageIndex: 0, // 当前显示的图片索引
      imageRotation: 0, // 图片旋转角度
      imageScale: 1, // 图片缩放比例
      imageLoading: false, // 图片加载状态
      showLargePreview: false, // 默认显示网格视图
      selectedImageIndex: -1, // 当前选中的网格图片索引
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  created() {
    // 加载权限列表
    this.loadPermissions()

    // 页面加载时重置查询条件
    this.searchReset()
  },
  methods: {
    // 加载权限
    loadPermissions() {
      // 从sessionStorage获取权限
      let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || '[]')

      // 如果sessionStorage中没有权限，尝试从localStorage获取
      if (!authList || authList.length === 0) {
        authList = JSON.parse(localStorage.getItem(USER_AUTH) || '[]')
      }

      // 从按钮权限中获取
      const buttonAuth = JSON.parse(
        sessionStorage.getItem(SYS_BUTTON_AUTH) || localStorage.getItem(SYS_BUTTON_AUTH) || '[]'
      )

      // 合并权限
      if (buttonAuth && buttonAuth.length > 0) {
        authList = authList.concat(buttonAuth)
      }

      // 提取action字段
      this.permissionList = authList.map((auth) => auth.action || auth)
    },

    // 判断是否有权限
    hasPermission(permission) {
      if (!permission) return true // 如果未指定权限，默认有权限

      // 检查权限列表中是否包含指定权限
      if (this.permissionList.includes(permission)) {
        return true
      }

      // 检查权限列表中是否包含以逗号分隔的多个权限
      for (let perm of this.permissionList) {
        if (perm && perm.includes(',')) {
          const perms = perm.split(',')
          if (perms.includes(permission)) {
            return true
          }
        }
      }

      return false
    },

    // 加载数据方法
    loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      const params = this.getQueryParams()
      this.loading = true
      inventoryList(params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || []
            this.ipagination.total = res.result.total || 0
          } else {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    // 处理仓库变更
    handleWarehouseChange(value) {
      this.warehouseId = value
      this.queryParam.locationId = ''
    },

    // 处理物料选择变化
    handleMaterialChange(value, materials) {
      if (materials && materials.length > 0) {
        const material = materials[0]
        this.queryParam.materialName = material.materialName
      } else {
        this.queryParam.materialName = ''
      }
    },

    // 处理物料类型变化
    handleMaterialTypeChange(value) {
      this.materialType = value
      this.queryParam.materialCode = ''
    },

    // 获取库存状态颜色
    getStockStatusColor(status) {
      // 确保status为数字类型
      const statusNum = parseInt(status)

      switch (statusNum) {
        case 1:
          return 'green' // 正常
        case 2:
          return 'red' // 超过上限
        case 3:
          return 'orange' // 低于下限
        default:
          return 'blue'
      }
    },

    // 获取物料类型颜色 型材1 配件2 辅件3 其他4 余料5 半料6
    getMaterialTypeColor(type) {
      // 确保type为数字类型
      const typeNum = parseInt(type)

      switch (typeNum) {
        case 1:
          return 'blue'
        case 2:
          return 'green'
        case 3:
          return 'purple'
        case 4:
          return 'pink'
        case 5:
          return 'red'
        case 6:
          return 'yellow'
      }
    },

    // 打开出库模态框
    handleOutbound(record) {
      this.$refs.outboundModal.show(record)
    },

    // 打开移库模态框
    handleMove(record) {
      this.$refs.moveModal.show(record)
    },

    // 打开调整模态框
    handleAdjust(record) {
      this.adjustRecord = { ...record }
      this.adjustForm = {
        adjustType: 'increase',
        quantity: null,
        reason: '',
      }
      this.adjustVisible = true
    },

    // 处理历史记录
    handleHistory(record) {
      this.$refs.historyModal.show(record)
    },

    // 调整类型变化处理
    onAdjustTypeChange(e) {
      // 重置数量
      this.adjustForm.quantity = null
    },

    // 获取调整后数量
    getAdjustedQuantity() {
      if (!this.adjustForm.quantity || !this.adjustRecord.quantity) {
        return this.adjustRecord.quantity || 0
      }

      const currentQty = parseFloat(this.adjustRecord.quantity)
      const adjustQty = parseFloat(this.adjustForm.quantity)

      if (this.adjustForm.adjustType === 'increase') {
        return (currentQty + adjustQty).toFixed(2)
      } else {
        return (currentQty - adjustQty).toFixed(2)
      }
    },

    // 确认库存调整
    handleAdjustOk() {
      this.$refs.adjustForm.validate((valid) => {
        if (valid) {
          this.adjustLoading = true

          // 计算调整后的最终数量
          const currentQty = parseFloat(this.adjustRecord.quantity)
          const adjustQty = parseFloat(this.adjustForm.quantity)
          const finalQuantity =
            this.adjustForm.adjustType === 'increase' ? currentQty + adjustQty : currentQty - adjustQty

          // 构建调整参数
          const adjustData = {
            inventory: {
              id: this.adjustRecord.id,
              materialCode: this.adjustRecord.materialCode,
              materialName: this.adjustRecord.materialName,
              warehouseId: this.adjustRecord.warehouseId,
              locationId: this.adjustRecord.locationId,
              quantity: this.adjustRecord.quantity,
              batchNo: this.adjustRecord.batchNo,
            },
            quantity: finalQuantity, // 传递调整后的最终数量
            adjustType: this.adjustForm.adjustType, // 添加调整类型参数
            businessType: '30', // 库存调整业务类型
            businessNo: 'ADJ' + new Date().getTime(), // 生成调整单号
            operator: (this.$store.getters.userInfo && this.$store.getters.userInfo.username) || 'system',
            remark: this.adjustForm.reason,
          }

          // 调用后端接口
          this.$http
            .post('/wms/inventory/adjust', adjustData)
            .then((res) => {
              if (res.success) {
                this.$message.success('库存调整成功！')
                this.adjustVisible = false
                this.loadData() // 刷新列表
              } else {
                this.$message.error(res.message || '库存调整失败！')
              }
            })
            .catch((err) => {
              console.error('库存调整失败:', err)
              this.$message.error('库存调整失败，请稍后重试！')
            })
            .finally(() => {
              this.adjustLoading = false
            })
        }
      })
    },

    // 取消库存调整
    handleAdjustCancel() {
      this.adjustVisible = false
      this.adjustRecord = {}
      this.adjustForm = {
        adjustType: 'increase',
        quantity: null,
        reason: '',
      }
    },

    // 打开编辑模态框
    handleEdit(record) {
      this.$refs.editModal.show(record)
    },

    // 模态框操作完成回调
    handleModalOk() {
      this.loadData()
    },

    // 切换高级查询
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },

    // 获取图片URL
    getImageUrl(text) {
      if (!text) return ''
      try {
        // 如果text是对象，避免[object Object]错误
        if (typeof text === 'object') {
          console.warn('图片路径不应该是对象:', JSON.stringify(text))
          return ''
        }

        // 检查是否有多个图片路径
        const imageArray = text.split(',')
        if (imageArray && imageArray.length > 0) {
          // 获取第一张图片
          const firstImage = imageArray[0].trim()
          if (!firstImage) return ''

          return window._CONFIG['domianURL'] + '/sys/common/static/' + firstImage
        }
        return ''
      } catch (error) {
        console.error('获取文件URL失败:', error, '原始数据:', text)
        return ''
      }
    },

    // 处理图片加载错误
    handleImageError(event) {
      console.error('图片加载失败', event)
      // 设置为空白图片
      event.target.src =
        ''
      event.target.alt = '图片加载失败'
    },

    // 处理图片加载完成
    handleImageLoad() {
      this.imageLoading = false
    },

    // 放大图片
    zoomIn() {
      this.imageScale *= 1.2
      this.applyImageTransform()
    },

    // 缩小图片
    zoomOut() {
      this.imageScale /= 1.2
      this.applyImageTransform()
    },

    // 向左旋转图片
    rotateLeft() {
      this.imageRotation -= 90
      this.applyImageTransform()
    },

    // 向右旋转图片
    rotateRight() {
      this.imageRotation += 90
      this.applyImageTransform()
    },

    // 重置图片变换
    resetImage() {
      this.imageRotation = 0
      this.imageScale = 1
      this.applyImageTransform()
    },

    // 应用图片变换
    applyImageTransform() {
      const img = document.querySelector('.image-preview-selected .image-slide img')
      if (img) {
        img.style.transform = `rotate(${this.imageRotation}deg) scale(${this.imageScale})`
        img.style.maxWidth = this.imageScale > 1 ? 'none' : '100%'
      }
    },

    // 预览图片
    handlePreview(images) {
      if (!images) return

      try {
        // 如果images是对象，避免[object Object]错误
        if (typeof images === 'object') {
          console.warn('预览图片路径不应该是对象:', JSON.stringify(images))
          return
        }

        // 获取所有图片路径
        const imageArray = images.split(',').filter((img) => img && img.trim() !== '')
        if (imageArray.length === 0) return

        // 重置图片变换
        this.imageRotation = 0
        this.imageScale = 1
        this.imageLoading = true // 设置加载状态

        // 构建预览图片列表
        this.previewImages = imageArray.map((img) => {
          const imgPath = img.trim()
          // 使用后端提供的正确URL格式：/sys/common/static/
          const src = window._CONFIG['domianURL'] + '/sys/common/static/' + imgPath

          console.log('预览图片路径:', imgPath, '处理后:', src)
          return src
        })
        this.currentImageIndex = 0 // 重置当前图片索引
        this.previewVisible = true // 显示预览模态框
        this.selectedImageIndex = 0 // 默认选中第一张图片
        this.showLargePreview = imageArray.length === 1 // 如果只有一张图片，直接显示大图预览

        // 添加键盘事件监听
        this.$nextTick(() => {
          if (this.$refs.previewContainer) {
            this.$refs.previewContainer.focus()

            // 监听键盘事件
            window.addEventListener('keydown', this.handleKeyDown)
          }
        })
      } catch (error) {
        console.error('处理预览图片出错:', error, '原始数据:', images)
        this.imageLoading = false
      }
    },

    // 关闭预览模态框时的处理
    handleClosePreview() {
      this.previewVisible = false
      // 移除键盘事件监听
      window.removeEventListener('keydown', this.handleKeyDown)
    },

    // 获取第一张图片的URL - 保留旧方法以兼容现有代码
    getFirstImageUrl(images) {
      return this.getImageUrl(images)
    },

    // 获取图片数量
    getImageCount(images) {
      if (!images) return 0

      try {
        // 如果images是对象，避免[object Object]错误
        if (typeof images === 'object') {
          console.warn('图片路径不应该是对象:', JSON.stringify(images))
          return 0
        }

        const imageArray = images.split(',')
        return imageArray.filter((img) => img && img.trim() !== '').length
      } catch (error) {
        console.error('获取图片数量出错:', error)
        return 0
      }
    },

    // 查看图片
    handleViewImages(images) {
      if (!images) return
      const imageArray = images.split(',').filter((img) => img.trim() !== '')
      if (imageArray.length === 0) return

      const imgList = imageArray.map((img) => {
        return {
          src: window._CONFIG['domianURL'] + '/sys/common/static' + img,
        }
      })

      this.$preview({
        images: imgList,
      })
    },

    // 处理轮播图片变化 - 不再需要，但保留兼容性
    handleCarouselChange(current) {
      this.currentImageIndex = current
      // 重置图片变换
      this.resetImage()
    },

    // 跳转到指定索引的图片
    goToSlide(index) {
      if (this.currentImageIndex === index) return
      this.currentImageIndex = index
      this.selectedImageIndex = index
      // 重置图片变换
      this.resetImage()
    },

    // 切换视图模式 (网格/大图)
    toggleViewMode() {
      this.showLargePreview = !this.showLargePreview
    },

    // 选中网格图片
    selectImage(index) {
      this.selectedImageIndex = index
      this.currentImageIndex = index
      this.showLargePreview = true // 切换到大图预览
      this.resetImage() // 重置图片变换
    },

    // 键盘快捷键处理
    handleKeyDown(e) {
      if (!this.previewVisible) return

      switch (e.key) {
        case 'ArrowLeft':
          this.prevImage()
          break
        case 'ArrowRight':
          this.nextImage()
          break
        case 'Escape':
          this.previewVisible = false
          break
        case ' ': // 空格键
          this.toggleViewMode()
          break
      }
    },

    // 上一张图片
    prevImage() {
      if (this.previewImages.length <= 1) return

      let newIndex = this.currentImageIndex - 1
      if (newIndex < 0) {
        newIndex = this.previewImages.length - 1
      }

      this.goToSlide(newIndex)
    },

    // 下一张图片
    nextImage() {
      if (this.previewImages.length <= 1) return

      let newIndex = this.currentImageIndex + 1
      if (newIndex >= this.previewImages.length) {
        newIndex = 0
      }

      this.goToSlide(newIndex)
    },

    // 切换全屏模式
    toggleFullscreen() {
      const container = document.querySelector('.image-preview-container')
      if (!document.fullscreenElement) {
        if (container.requestFullscreen) {
          container.requestFullscreen()
        } else if (container.mozRequestFullScreen) {
          // Firefox
          container.mozRequestFullScreen()
        } else if (container.webkitRequestFullscreen) {
          // Chrome, Safari
          container.webkitRequestFullscreen()
        } else if (container.msRequestFullscreen) {
          // IE/Edge
          container.msRequestFullscreen()
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen()
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen()
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen()
        }
      }
    },

    // 下载当前图片
    downloadImage() {
      if (this.previewImages.length === 0) return

      const currentImage = this.previewImages[this.currentImageIndex]
      const link = document.createElement('a')
      link.href = currentImage

      // 从URL中提取文件名
      const fileName = currentImage.split('/').pop() || `物料图片_${new Date().getTime()}.jpg`
      link.download = fileName

      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    // 重写getQueryParams方法，处理日期格式
    getQueryParams() {
      // 调用混入的getQueryParams
      let params = Object.assign({}, this.$data.queryParam)

      // 处理日期格式
      if (params.planInboundTime) {
        params.planInboundTime = moment(params.planInboundTime).format('YYYY-MM-DD')
      }

      if (params.actualInboundTime) {
        params.actualInboundTime = moment(params.actualInboundTime).format('YYYY-MM-DD')
      }

      // 分页参数
      params.pageNo = this.ipagination.current
      params.pageSize = this.ipagination.pageSize

      return params
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/common.less';
.ant-card-body .table-operator {
  margin-bottom: 18px;
}
.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}
.anty-row-operator button {
  margin: 0 5px;
}
.ant-btn-danger {
  background-color: #ffffff;
}
.ant-modal-cust-warp {
  height: 100%;
}
.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto;
}
.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden;
}
.table-wrapper {
  height: calc(100vh - 280px);
  overflow: visible;
}
.table-wrapper .ant-table-body {
  min-height: 300px;
}
.table-wrapper .ant-pagination {
  margin: 16px 0;
}
/* 确保表格横向滚动条始终可见 */
.table-wrapper .ant-table {
  overflow: visible;
}
.table-wrapper .ant-table-content {
  overflow: visible;
}
.table-wrapper .ant-table-scroll {
  overflow: visible;
}
.table-wrapper .ant-table-body {
  overflow-x: auto !important;
  overflow-y: auto !important;
}
/* 固定横向滚动条在表格底部 */
.table-wrapper .ant-table-body::-webkit-scrollbar {
  height: 8px;
}
.table-wrapper .ant-table-body::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}
.table-wrapper .ant-table-body::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}
.table-wrapper .ant-table-body::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
.image-preview-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  outline: none; /* 移除focus时的轮廓线 */
}
.image-preview-container .image-slide {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.image-preview-container .image-slide img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  transition: transform 0.3s ease;
}
.image-preview-container .image-preview-counter {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 14px;
  z-index: 10;
}
.image-preview-container .image-preview-thumbnails {
  display: flex;
  justify-content: center;
  margin-top: 10px;
  gap: 5px;
  max-width: 100%;
  overflow-x: auto;
  padding: 5px 0;
}
.image-preview-container .image-thumbnail {
  width: 50px;
  height: 50px;
  border: 2px solid transparent;
  cursor: pointer;
  overflow: hidden;
  flex-shrink: 0;
  transition: all 0.2s ease;
}
.image-preview-container .image-thumbnail:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.image-preview-container .image-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.image-preview-container .image-thumbnail.active {
  border-color: #1890ff;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.image-preview-container .image-preview-controls {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  padding: 8px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  z-index: 10;
  transition: opacity 0.3s ease;
}
.image-preview-container:not(:hover) .image-preview-controls {
  opacity: 0.6;
}
.image-preview-container .image-preview-controls .ant-btn {
  color: white;
  background: transparent;
  border-color: #d9d9d9;
}
.image-preview-container .image-preview-controls .ant-btn:hover {
  color: #1890ff;
  background: rgba(255, 255, 255, 0.2);
}
.image-preview-container .ant-carousel .slick-prev,
.image-preview-container .ant-carousel .slick-next {
  color: white;
  font-size: 20px;
  z-index: 9;
}
.image-preview-container .ant-carousel .slick-prev {
  left: 10px;
}
.image-preview-container .ant-carousel .slick-next {
  right: 10px;
}
/* 全屏模式样式 */
.image-preview-container:fullscreen {
  background-color: #000;
  padding: 20px;
}
.image-preview-container:fullscreen .image-slide img {
  max-height: calc(100vh - 150px);
}
/* 模态框样式 */
.image-preview-modal .ant-modal-content {
  background-color: rgba(0, 0, 0, 0.85);
}
.image-preview-modal .ant-modal-close {
  color: white;
}
.image-preview-modal .ant-modal-body {
  padding: 24px;
}
.image-grid-container {
  display: grid;
  grid-template-columns: repeat(5, 1fr); /* 默认每行5张图片 */
  gap: 15px; /* 图片之间的间距 */
  justify-content: center;
  padding: 15px;
  overflow-y: auto; /* 允许网格内容滚动 */
  max-height: 500px; /* 网格容器最大高度 */
  background-color: #f5f5f5;
  border-radius: 4px;
}
/* 响应式布局 */
@media screen and (max-width: 1600px) {
  .image-grid-container {
    grid-template-columns: repeat(4, 1fr); /* 较小屏幕每行4张图片 */
  }
}
@media screen and (max-width: 1200px) {
  .image-grid-container {
    grid-template-columns: repeat(3, 1fr); /* 平板每行3张图片 */
  }
}
@media screen and (max-width: 768px) {
  .image-grid-container {
    grid-template-columns: repeat(2, 1fr); /* 手机每行2张图片 */
  }
}
.image-grid-item {
  width: 100%;
  aspect-ratio: 1/1; /* 保持正方形 */
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #eee;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s ease;
  background-color: #fff;
  position: relative;
}
.image-grid-item.active {
  border-color: #1890ff;
  box-shadow: 0 0 10px rgba(24, 144, 255, 0.5);
}
.image-grid-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.image-grid-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.image-grid-item-index {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}
.view-toggle-container {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}
.image-preview-selected {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px;
  background-color: #000; /* 大图预览背景 */
}
.image-preview-selected .image-slide {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.image-preview-selected .image-slide img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  transition: transform 0.3s ease;
}
.image-preview-selected .image-preview-counter {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 14px;
  z-index: 10;
}
.image-preview-selected .image-preview-controls {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  padding: 8px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  z-index: 10;
  transition: opacity 0.3s ease;
}
.image-preview-selected:not(:hover) .image-preview-controls {
  opacity: 0.6;
}
.image-preview-selected .image-preview-controls .ant-btn {
  color: white;
  background: transparent;
  border-color: #d9d9d9;
}
.image-preview-selected .image-preview-controls .ant-btn:hover {
  color: #1890ff;
  background: rgba(255, 255, 255, 0.2);
}
.image-preview-selected .ant-carousel .slick-prev,
.image-preview-selected .ant-carousel .slick-next {
  color: white;
  font-size: 20px;
  z-index: 9;
}
.image-preview-selected .ant-carousel .slick-prev {
  left: 10px;
}
.image-preview-selected .ant-carousel .slick-next {
  right: 10px;
}
</style> 